package com.piece.member.controller;

import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.constant.FrameWorkConstants;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.support.response.Select;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.web.controller.FrameWorkController;
import com.piece.member.model.UmsMemberLevel;
import com.piece.member.service.UmsMemberLevelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Api(tags = {"会员等级管理"})
@RequestMapping("/api/member/level")
public class UmsMemberLevelController extends FrameWorkController {

    @Resource
    private UmsMemberLevelService umsMemberLevelService;

    @PostMapping("/list")
    @AclPermission(code = "system:member:view")
    @ApiOperation(value = "查询会员等级列表")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public List list() {
        QueryTable queryTable = initTable();
        DataTable dataTable = umsMemberLevelService.findPage(queryTable);
        return dataTable.getData();
    }

    @PostMapping("/table")
    @AclPermission(code = "system:member:view")
    @ApiOperation(value = "查询会员等级分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        DataTable dataTable = umsMemberLevelService.findPage(queryTable);
        return success(dataTable);
    }

    @GetMapping("/load")
    @AclPermission(code = "system:member:view")
    @ApiOperation(value = "加载会员等级表单数据")
    @ApiImplicitParam(name="id", value = "主键")
    public AjaxResponse load() {
        long id = Convert.toLong(getRequest().getParameter("id"), 0L);
        UmsMemberLevel umsMemberLevel = new UmsMemberLevel();
        if (id != 0) {
            umsMemberLevel = umsMemberLevelService.findById(id);
        }
        return success(umsMemberLevel);
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "system:member:edit")
    @ApiOperation(value = "保存会员等级表单数据")
    @ApiImplicitParam(value = "会员等级数据", dataTypeClass = UmsMemberLevel.class, type = "body")
    public AjaxResponse save() {
        UmsMemberLevel umsMemberLevel;
        try {
            Long id = Convert.toLong(getRequest().getParameter("id"));
            if (null != id) {
                umsMemberLevel = umsMemberLevelService.findById(id);
            } else {
                umsMemberLevel = new UmsMemberLevel();
            }
            initDB(umsMemberLevel);
            umsMemberLevelService.insertOrUpdate(umsMemberLevel);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/{id}/change/{type}")
    @AclPermission(code = "system:member:edit")
    @ApiOperation(value = "更新会员等级特权")
    @ApiImplicitParam(value = "更新会员等级特权", dataTypeClass = UmsMemberLevel.class, type = "body")
    public AjaxResponse change(@PathVariable String id, @PathVariable String type) {
        try {
            UmsMemberLevel umsMemberLevel = new UmsMemberLevel();
            initDB(umsMemberLevel);
            umsMemberLevelService.change(id, type, umsMemberLevel);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/delete/{id}")
    @AclPermission(code = "system:member:delete")
    @ApiOperation(value = "删除会员等级数据")
    @ApiImplicitParam(name = "id", value = "主键", type = "path")
    public AjaxResponse delete(@PathVariable String id) throws Exception {
        umsMemberLevelService.delete(id);
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "system:member:delete")
    @ApiOperation(value = "删除会员等级数据")
    @ApiImplicitParam(name = "ids", value="主键集合")
    public AjaxResponse deleteBatch() throws Exception {
        String ids = getRequest().getParameter("ids");
        if (StringUtil.isNotEmpty(ids)) {
            umsMemberLevelService.delete(Convert.toLongArray(ids));
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @PostMapping("/select")
    @ApiOperation(value = "查询会员级别下拉列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "查询分页条件", dataTypeClass = Select.class, type = "body"),
            @ApiImplicitParam(name = "selected", value = "已选ID"),
            @ApiImplicitParam(name = "Q_name_S_LK", value = "等级名称")
    })
    public AjaxResponse select() {
        String selected = getRequest().getParameter("selected");
        QueryTable queryTable = initSelect("Q_name_S_LK");
        DataTable dataTable = umsMemberLevelService.findPage(queryTable);
        if (StringUtil.isNotEmpty(selected)) {
            selected = FrameWorkConstants.SPLIT_PARAM + selected + FrameWorkConstants.SPLIT_PARAM;
        }
        return success(tableToSelect(dataTable, selected));
    }

    private Select tableToSelect(DataTable dataTable, String selected) {
        Select select = Select.builder().build();
        List<UmsMemberLevel> postList = dataTable.getData();
        List<Select.Entity> entityList = postList.stream().map(level -> select.new Entity(Convert.toStr(level.getId()), Convert.toStr(level.getName()))).filter(entity -> {
            if (StringUtil.isNotEmpty(selected)) {
                if (selected.indexOf(FrameWorkConstants.SPLIT_PARAM + entity.getId() + FrameWorkConstants.SPLIT_PARAM) != -1) {
                    return true;
                }
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        select.setTotal(dataTable.getRecordsTotal());
        select.setData(entityList);
        return select;
    }
}
